<?php   
namespace app\api\controller\haipi;

use app\common\controller\Frontend;
use app\common\model\haipi\Comment as CommentModel;
use think\facade\Log;

class Comment extends Frontend {
    protected array $noNeedLogin = ["index"];   
    protected array $noNeedRight = ["*"];

    public function index() {
       

        $id = $this->request->get("article_id");
        $articleType = $this->request->get("article_type");
        if(empty($id) || empty($articleType)) { 
            $this->error("缺少参数");   
        }
        $list = CommentModel::with(['user'])
            ->where("article_id", $id)
            ->where("article_type", $articleType)
            ->where("status", 1)
            ->order("id", "desc")
            ->select()
            ->append(['owner', 'avatar_url', 'nick_name'])
            ->map(function ($item)  {
                if($this->auth->isLogin()){
                    $item['owner'] =  $item['user_id'] == $this->auth->id;
                    $item['has_like'] = in_array($this->auth->id, $item['like']);
                }else{
                    $item['owner'] = false;
                    $item['has_like'] = false;
                }
               
                $item['like_num'] = count($item['like']);
            
                return $item;
            });

        $this->success("获取成功", $list);
    }
    
    public function like(){
        $id = $this->request->post("id");
        $comment = CommentModel::where("id", $id)
        ->find();
        if(!$comment){
            $this->error("评论不存在");
        }
        if(in_array($this->auth->id,$comment->like) ){
            $comment->like = array_diff($comment->like, [$this->auth->id]);
        }else{
            $comment->like = array_merge($comment->like, [$this->auth->id]);
        }
        $comment->save();
        $this->success("ok");
    }

    public function del(){
        $id = $this->request->post("id");
        CommentModel::where(function($query) use ($id) {
            $query->where('id', $id)
                  ->where('user_id', $this->auth->id);
        })->whereOr('parent_id', $id)->delete();
        $this->success("ok");
    }

    public function add(){
        $data = $this->request->post();
        $validate = new \app\api\validate\haipi\Comment();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $data['user_id'] = $this->auth->id;
     
        CommentModel::create($data);
        $this->success("评论成功" ,$data);
    }
}